package email

import (
	"net/smtp"
	"strings"

	"github.com/jordan-wright/email"
	"github.com/spf13/viper"
)

type eMail struct {
	TO, Bcc, Cc []string
	Subject     string
	HTML        string
	AttachFile  string
	EmailServer *emailServer
}

type emailServer struct {
	Addr     string //发送地址 'smtp.qq.com:25'
	Host     string //smtp.qq.com
	Username string
	Password string
}

func defaultServer() *emailServer {
	cfg := viper.GetStringMapString("email")
	return &emailServer{
		Addr:     cfg["addr"],
		Host:     cfg["host"],
		Username: cfg["username"],
		Password: cfg["password"],
	}
}

func New(server ...*emailServer) *eMail {
	var EmailServer *emailServer
	if len(server) > 0 {
		EmailServer = server[0]
	} else {
		EmailServer = defaultServer()
	}

	return &eMail{EmailServer: EmailServer}
}

func (m *eMail) Send() error {
	mail := email.NewEmail()
	mail.From = m.EmailServer.Username
	mail.To = m.TO
	mail.Bcc = m.Bcc
	mail.Cc = m.Cc
	mail.Subject = m.Subject
	mail.HTML = []byte(m.HTML)
	if m.AttachFile != "" {
		for _, AttachFile := range strings.Split(m.AttachFile, ",") {
			_, e := mail.AttachFile(AttachFile)
			if e != nil {
				return e
			}
		}
	}

	return mail.Send(m.EmailServer.Addr, smtp.PlainAuth("", m.EmailServer.Username, m.EmailServer.Password, m.EmailServer.Host))
}

func Send(to string, subject string, html string, attachfile ...string) error {
	mail := New()
	TO := []string{}
	for _, v := range strings.Split(to, ",") {
		TO = append(TO, v)
	}
	mail.TO = TO
	mail.Subject = subject
	mail.HTML = html
	if len(attachfile) > 0 {
		mail.AttachFile = strings.Join(attachfile, ",")
	}

	return mail.Send()
}
